// 产品页面专用JavaScript功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化产品页面功能
    initProductTabs();
    initProductFilter();
    initProductAnimations();
    initComparisonTable();
    initCaseStudies();
});

// 产品分类标签功能
function initProductTabs() {
    const tabButtons = document.querySelectorAll('.tab-btn');
    const productDetails = document.querySelectorAll('.product-detail');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            
            // 更新标签状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // 过滤产品
            filterProducts(category, productDetails);
        });
    });
}

// 产品过滤功能
function filterProducts(category, productDetails) {
    productDetails.forEach(product => {
        const productCategory = product.getAttribute('data-category');
        
        if (category === 'all' || productCategory === category) {
            product.classList.remove('hidden');
            product.classList.add('visible');
        } else {
            product.classList.add('hidden');
            product.classList.remove('visible');
        }
    });
    
    // 添加过滤动画效果
    setTimeout(() => {
        productDetails.forEach(product => {
            if (product.classList.contains('visible')) {
                product.style.display = 'block';
            } else {
                product.style.display = 'none';
            }
        });
    }, 300);
}

// 产品动画效果
function initProductAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);
    
    // 观察需要动画的元素
    const animateElements = document.querySelectorAll('.product-detail, .case-item, .comparison-table');
    animateElements.forEach(el => {
        el.classList.add('animate-element');
        observer.observe(el);
    });
}

// 产品对比表格功能
function initComparisonTable() {
    const table = document.querySelector('.comparison-table table');
    
    if (table) {
        // 添加表格悬停效果
        const rows = table.querySelectorAll('tbody tr');
        rows.forEach(row => {
            row.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f8fafc';
            });
            
            row.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
            });
        });
        
        // 添加列悬停效果
        const cells = table.querySelectorAll('td');
        cells.forEach(cell => {
            const columnIndex = Array.from(cell.parentNode.children).indexOf(cell);
            
            cell.addEventListener('mouseenter', function() {
                const allCellsInColumn = table.querySelectorAll(`td:nth-child(${columnIndex + 1})`);
                allCellsInColumn.forEach(cellInColumn => {
                    cellInColumn.style.backgroundColor = '#e0f2fe';
                });
            });
            
            cell.addEventListener('mouseleave', function() {
                const allCellsInColumn = table.querySelectorAll(`td:nth-child(${columnIndex + 1})`);
                allCellsInColumn.forEach(cellInColumn => {
                    cellInColumn.style.backgroundColor = '';
                });
            });
        });
    }
}

// 客户案例功能
function initCaseStudies() {
    const caseItems = document.querySelectorAll('.case-item');
    
    caseItems.forEach(item => {
        item.addEventListener('click', function() {
            // 添加点击效果
            this.style.transform = 'scale(0.98)';
            setTimeout(() => {
                this.style.transform = '';
            }, 150);
        });
    });
}

// 申请演示功能
function requestDemo(productName) {
    // 创建演示申请表单
    const modal = createDemoModal(productName);
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
}

// 创建演示申请模态框
function createDemoModal(productName) {
    const modal = document.createElement('div');
    modal.className = 'demo-modal';
    modal.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h3>申请产品演示</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <p>您正在申请 <strong>${productName}</strong> 的产品演示</p>
                <form id="demoForm">
                    <div class="form-group">
                        <label for="demoName">姓名 *</label>
                        <input type="text" id="demoName" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="demoCompany">公司名称 *</label>
                        <input type="text" id="demoCompany" name="company" required>
                    </div>
                    <div class="form-group">
                        <label for="demoEmail">邮箱 *</label>
                        <input type="email" id="demoEmail" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="demoPhone">电话</label>
                        <input type="tel" id="demoPhone" name="phone">
                    </div>
                    <div class="form-group">
                        <label for="demoMessage">需求描述</label>
                        <textarea id="demoMessage" name="message" rows="4" placeholder="请描述您的具体需求..."></textarea>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeDemoModal()">取消</button>
                        <button type="submit" class="btn btn-primary">提交申请</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    // 添加模态框样式
    const style = document.createElement('style');
    style.textContent = `
        .demo-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        
        .demo-modal.show {
            opacity: 1;
            visibility: visible;
        }
        
        .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }
        
        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            transition: transform 0.3s ease;
        }
        
        .demo-modal.show .modal-content {
            transform: translate(-50%, -50%) scale(1);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .modal-header h3 {
            margin: 0;
            color: var(--text-color);
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #6b7280;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.3s ease;
        }
        
        .modal-close:hover {
            background: #f3f4f6;
            color: var(--text-color);
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-body p {
            margin-bottom: 1.5rem;
            color: var(--text-light);
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: var(--text-color);
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary-color);
        }
        
        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 1.5rem;
        }
        
        @media (max-width: 480px) {
            .modal-content {
                width: 95%;
                margin: 1rem;
            }
            
            .form-actions {
                flex-direction: column;
            }
        }
    `;
    
    if (!document.querySelector('#demo-modal-styles')) {
        style.id = 'demo-modal-styles';
        document.head.appendChild(style);
    }
    
    // 绑定事件
    const closeBtn = modal.querySelector('.modal-close');
    const overlay = modal.querySelector('.modal-overlay');
    const form = modal.querySelector('#demoForm');
    
    closeBtn.addEventListener('click', closeDemoModal);
    overlay.addEventListener('click', closeDemoModal);
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        handleDemoSubmission(this, productName);
    });
    
    // ESC键关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.classList.contains('show')) {
            closeDemoModal();
        }
    });
    
    return modal;
}

// 关闭演示模态框
function closeDemoModal() {
    const modal = document.querySelector('.demo-modal');
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.remove();
        }, 300);
    }
}

// 处理演示申请提交
function handleDemoSubmission(form, productName) {
    const formData = new FormData(form);
    const data = Object.fromEntries(formData);
    
    // 简单验证
    if (!data.name || !data.company || !data.email) {
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    
    if (!isValidEmail(data.email)) {
        showNotification('请输入有效的邮箱地址', 'error');
        return;
    }
    
    // 模拟提交
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    
    submitBtn.textContent = '提交中...';
    submitBtn.disabled = true;
    
    setTimeout(() => {
        showNotification(`演示申请已提交！我们将尽快联系您安排 ${productName} 的演示。`, 'success');
        closeDemoModal();
    }, 2000);
}

// 下载产品资料
function downloadBrochure(productName) {
    // 模拟下载
    showNotification(`正在准备 ${productName} 的产品资料...`, 'info');
    
    setTimeout(() => {
        // 创建虚拟下载链接
        const link = document.createElement('a');
        link.href = '#'; // 实际项目中这里应该是真实的PDF链接
        link.download = `${productName}-产品资料.pdf`;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showNotification(`${productName} 产品资料下载完成！`, 'success');
    }, 1500);
}

// 产品搜索功能（可选）
function initProductSearch() {
    const searchInput = document.createElement('input');
    searchInput.type = 'text';
    searchInput.placeholder = '搜索产品...';
    searchInput.className = 'product-search';
    
    const searchContainer = document.querySelector('.product-categories .container');
    if (searchContainer) {
        searchContainer.appendChild(searchInput);
        
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const productDetails = document.querySelectorAll('.product-detail');
            
            productDetails.forEach(product => {
                const title = product.querySelector('h2').textContent.toLowerCase();
                const description = product.querySelector('.product-subtitle').textContent.toLowerCase();
                
                if (title.includes(searchTerm) || description.includes(searchTerm)) {
                    product.style.display = 'block';
                } else {
                    product.style.display = 'none';
                }
            });
        });
    }
}

// 产品分享功能
function shareProduct(productName, productUrl) {
    if (navigator.share) {
        navigator.share({
            title: `${productName} - 创新科技`,
            text: `查看创新科技的${productName}产品介绍`,
            url: productUrl
        });
    } else {
        // 复制链接到剪贴板
        navigator.clipboard.writeText(productUrl).then(() => {
            showNotification('产品链接已复制到剪贴板', 'success');
        });
    }
}

// 产品收藏功能（本地存储）
function toggleProductFavorite(productName) {
    const favorites = JSON.parse(localStorage.getItem('productFavorites') || '[]');
    const index = favorites.indexOf(productName);
    
    if (index > -1) {
        favorites.splice(index, 1);
        showNotification(`已取消收藏 ${productName}`, 'info');
    } else {
        favorites.push(productName);
        showNotification(`已收藏 ${productName}`, 'success');
    }
    
    localStorage.setItem('productFavorites', JSON.stringify(favorites));
    updateFavoriteButtons();
}

// 更新收藏按钮状态
function updateFavoriteButtons() {
    const favorites = JSON.parse(localStorage.getItem('productFavorites') || '[]');
    const favoriteButtons = document.querySelectorAll('.favorite-btn');
    
    favoriteButtons.forEach(btn => {
        const productName = btn.getAttribute('data-product');
        if (favorites.includes(productName)) {
            btn.classList.add('favorited');
            btn.innerHTML = '<i class="fas fa-heart"></i>';
        } else {
            btn.classList.remove('favorited');
            btn.innerHTML = '<i class="far fa-heart"></i>';
        }
    });
}

// 页面加载完成后的初始化
window.addEventListener('load', function() {
    // 初始化搜索功能（如果需要）
    // initProductSearch();
    
    // 更新收藏按钮状态
    updateFavoriteButtons();
    
    // 添加页面加载完成的类
    document.body.classList.add('loaded');
});

// 错误处理
window.addEventListener('error', function(e) {
    console.error('产品页面错误:', e.error);
});
